package tools

import (
	"github.com/leonscriptcc/bondman/configs"
	"github.com/patrickmn/go-cache"
	"log"
	"time"
)

var CacheMan *cacheMan

type cacheMan struct {
	counts int
	caches *cache.Cache
}

func init() {
	c := cache.New(5*time.Minute, cache.NoExpiration)
	CacheMan = &cacheMan{caches: c}
}

// GSet 先获取在设置缓存，如果返回为false，则说明缓存已经存在，set失败
func (cm *cacheMan) GSet(key string) bool {
	cm.caches.DeleteExpired()
	cm.counts = cm.caches.ItemCount()
	// 缓存数量控制
	if cm.counts > 10 {
		return false
	}

	// 如果能查到缓存，说明未过期，不予处理
	_, ok := cm.caches.Get(key)
	if ok {
		return false
	}

	// 加入缓存
	if err := cm.caches.Add(key, struct{}{}, time.Duration(configs.Parameters.Interval)*time.Minute); err != nil {
		log.Println(err)
		return false
	}

	return true
}
